class TwitterSource < Source
  def fetch
    super
    
    # if we have a thread obj already, make sure it's alive. otherwise create a thread
    reason = nil
    if !@thread
      reason = "Stream thread doesn't exist. Restarting stream."
    elsif !@thread.alive?
      puts @thread.inspect
      reason = "Stream thread died. Restarting stream."
    end
    
    if reason
      add_info(reason)
      restart_thread
    end
    
    update_deadline

    @fetched ||= 0
    f = @fetched
    @fetched = 0
    return f
  end

  def default_update_freq
    10
  end
  
  def reset!
    super
    restart_thread
  end
  
  def cleanup
    if @thread
      add_warning("Going away. Stopping thread.")
      @thread.kill
    end
  end
  
  def parse_one
    # get the next report in the queue
    json = dequeue
    
    # bail if nothing to parse
    if json.nil?
      return false 
    end
    
    # parse json
    r = ActiveSupport::JSON.decode(json).symbolize_keys
    
    # parse the date
    r[:authored_at] = Time.parse(r[:authored_at].to_s) unless r[:authored_at].is_a?(Time)
    r[:url] = "http://twitter.com/#!/#{r[:author]}/status/#{r[:orig_id]}"
    
    # create the report
    create_report(r)
    return true
  end
  
  def restart_thread
    # kill the current thread if it exists and is alive
    @thread.kill if @thread && @thread.alive?
    
    # don't do anything if the source is disabled
    return unless enabled?
    
    if keywords_list.empty?
      add_error("Twitter source has no keywords and has been disabled.")
      disable!
    else
      add_info("Now tracking keywords: #{keywords_list.join(', ')}")
      @thread = Thread.new(self) do |source|
        TweetStream.configure do |config|
          config.consumer_key = configatron.twitter_consumer_key
          config.consumer_secret = configatron.twitter_consumer_secret
          config.oauth_token = configatron.twitter_oauth_token
          config.oauth_token_secret = configatron.twitter_oauth_token_secret
          config.auth_method = :oauth
          config.parser = :json_gem
        end
        
        TweetStream::Client.new.on_limit do |skip_count|
          add_warning("The stream was rate limited (skip count: #{skip_count}).")
        end.on_error do |error|
          add_error(error)
        end.track(*source.keywords_list) do |t|
          #Rails.logger.info("[TwitterSource] Got tweet: #{t.text}")
          # make sure the language matches (if applicable)
          if source.accepts_lang?(t.user.lang)
            # write the twitter message to a file for parsing
            enqueue("#{t.id}.json", {:orig_id => t.id, :authored_at => t.created_at, :author => t.user.screen_name, :content => t.text.gsub("\n", " ")}.to_json)
            @fetched ||= 0
            @fetched += 1
          end
        end
      end
    end
  end
end